package com.md24housecall.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.activity.IHealthActivity;
import com.md24housecall.activity.LoginActivity;
import com.md24housecall.activity.R;
import com.md24housecall.adapter.MultiIHealthAdapter;
import com.md24housecall.adapter.MultiIHealthAdapter.OnDeleteListener;
import com.md24housecall.manager.CacheManager;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.model.UserAccountIHealth;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.PagingListView;
import com.md24housecall.view.PagingListView.PagingListViewListener;
import com.md24housecall.view.RatioImageView;
import com.md24housecall.view.RatioRelativeLayout;

public final class MultiIHealthFragment extends HomeFragment implements OnItemClickListener,PagingListViewListener {
	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	private int mTabPosition = 0;
	private GlobalConstant constant=GlobalConstant.getInstance();
//	private boolean isGetData=false;
	private Utils util=Utils.getInstance();
	private AQuery mAQuery;
	private PagingListView lvMultiAccount;
	private Button btnAddAccount;
	private CacheManager cacheManager;
	private String multiAccountUrl="";
	private MultiIHealthAdapter adapter;
	private List<UserAccountIHealth> listUser=new ArrayList<UserAccountIHealth>();
	private ProgressBar mProgressBar;
	private RatioImageView mImgHeader;
	private RatioRelativeLayout relBackground;
	private boolean isRetry=false;
	private int mRetry=0;
	private final int MAX_RETRY=3;

	public static MultiIHealthFragment newInstance(int tabPosition) {
		MultiIHealthFragment fragment = new MultiIHealthFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	private void initialize() {
		mAQuery=new AQuery(getActivity());
		relBackground=(RatioRelativeLayout)mainView.findViewById(R.id.relBackground);
		relBackground.setRatio(DimenManager.WIDTH_BACKGROUND_PATIENT,
				DimenManager.HEIGHT_BACKGROUND_PATIENT);
		mImgHeader = (RatioImageView) mainView.findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mProgressBar=(ProgressBar)mainView.findViewById(R.id.progressBar);
		cacheManager = CacheManager.getInstance(getActivity());
		btnAddAccount=(Button)mainView.findViewById(R.id.btnAddAccount);
		lvMultiAccount=(PagingListView)mainView.findViewById(R.id.lvIhealthAccount);
		lvMultiAccount.setPullLoadEnable(false);
		lvMultiAccount.setPullRefreshEnable(true);
		lvMultiAccount.setOnItemClickListener(this);
		lvMultiAccount.setPagingListViewListener(this);
		btnAddAccount.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//clear database
				startActivity(new Intent(getActivity(),LoginActivity.class));
			}
		});
	}

	private void confirmDelete(final int position){
	      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
	      alertDialogBuilder.setMessage(R.string.msg_ihealth_delete_confirm);
	      alertDialogBuilder.setPositiveButton(R.string.button_yes, 
	      new DialogInterface.OnClickListener() {
			
	         @Override
	         public void onClick(DialogInterface arg0, int arg1) {
	        	mRetry=0;
				mAQuery.progress(mProgressBar).ajax(String.format(UrlBuilder.URL_DELETE_IHEALTH_ACCOUNT, listUser.get(position).getIhealthId(),util.getCode(getActivity())),String.class,new AjaxCallback<String>(){
					@Override
					public void callback(String url, String object,
							AjaxStatus status) {
						// TODO Auto-generated method stub
//						super.callback(url, object, status);
//						if(isRetry){
//							if(jsonArray==null){
//								if(mRetry<MAX_RETRY){
//									refreshListUser();
//									mRetry++;
//									return;
//								}
//							}
//							mRetry=0;
//						}
						android.util.Log.d(GlobalConstant.TAG, "result delete: "+object);
						if(status.getCode()==200){
//							if(mProgressBar.getVisibility()==View.GONE)
//								mProgressBar.setVisibility(View.VISIBLE);
							refreshListUser();
						}
					}
				});
	         }
	      });
	      alertDialogBuilder.setNegativeButton(R.string.button_no, 
	      new DialogInterface.OnClickListener() {
				
	         @Override
	         public void onClick(DialogInterface dialog, int which) {
	            
			 }
	      });
		    
	      AlertDialog alertDialog = alertDialogBuilder.create();
	      alertDialog.show();
		    
	   }
	
	private void refreshListUser(){
		mAQuery.ajax(multiAccountUrl, JSONArray.class, new AjaxCallback<JSONArray>(){
			@Override
			public void callback(String url, JSONArray jsonArray, AjaxStatus status) {
				if(isRetry){
					if(jsonArray==null){
						if(mRetry<MAX_RETRY){
							refreshListUser();
							mRetry++;
							return;
						}
					}
					mRetry=0;
				}
//				MyLog.d(GlobalConstant.TAG, "getPartnerFromApi status: "+status.getCode());
				if(mProgressBar.getVisibility()==View.VISIBLE)
					mProgressBar.setVisibility(View.GONE);
				lvMultiAccount.stopRefresh();
				if(status.getCode()==200){
					android.util.Log.d(GlobalConstant.TAG,"url json user ihealth: "+url);
					android.util.Log.d(GlobalConstant.TAG,"json user ihealth: "+jsonArray.toString());
					android.util.Log.d(GlobalConstant.TAG,"json user ihealth len: "+jsonArray.length());
					android.util.Log.d(GlobalConstant.TAG,"listUser.size(): "+listUser.size());
					int len = 0;
					if(jsonArray!=null)
						len=jsonArray.length();
					if(listUser!=null && listUser.size()>0)
						listUser.clear();
					if(len>0){
						lvMultiAccount.setVisibility(View.VISIBLE);
//						txvNoData.setVisibility(View.GONE);
						for(int i=0;i<len;i++){
							try {
								JSONObject json_data = jsonArray.getJSONObject(i);
								UserAccountIHealth user=new UserAccountIHealth();
								user.setId(json_data.getString("id"));
								user.setToken(json_data.getString("token"));
								user.setCode(json_data.getString("code"));
								user.setIhealthId(json_data.getString("ihealth_id"));
								user.setUserInfo(json_data.getString("user_info"));
								listUser.add(user);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}else{
						lvMultiAccount.setVisibility(View.VISIBLE);
//						txvNoData.setVisibility(View.VISIBLE);
					}
				}else{
					lvMultiAccount.setVisibility(View.VISIBLE);
					Toast.makeText(getActivity(), status.getMessage(), Toast.LENGTH_LONG).show();
				}
				if(adapter==null /*|| listUser.size()==0*/){
					adapter=new MultiIHealthAdapter(getActivity(), listUser);
					adapter.setOnDeleteListener(new OnDeleteListener() {
						
						@Override
						public void onDeleteComplete(int position) {
							// TODO Auto-generated method stub
							android.util.Log.d(GlobalConstant.TAG,"position: "+position);
							confirmDelete(position);
						}
					});
					lvMultiAccount.setAdapter(adapter);
				}else{
					adapter.notifyDataSetChanged();
				}
			}
		});
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MyLog.d(GlobalConstant.TAG,"constant.isUpdateIhealthUser: "+constant.isUpdateIhealthUser);
		if(constant.isUpdateIhealthUser){
			constant.isUpdateIhealthUser=false;
//			if(mProgressBar.getVisibility()==View.GONE)
//				mProgressBar.setVisibility(View.VISIBLE);
			refreshListUser();
		}
	}
	@Override
	protected View initView(LayoutInflater inflater,ViewGroup container) {
		// TODO Auto-generated method stub
		MyLog.d(GlobalConstant.TAG, "multi ihealth");
		return inflater.inflate(R.layout.multi_ihealth, container, false);
	}
	
	@Override
	protected void initLayout() {
		// TODO Auto-generated method stub
		try{
			initialize();
			multiAccountUrl=String.format(UrlBuilder.URL_GET_MULTI_IHEALTH, util.getCode(getActivity()));
		}catch (Exception e) {
			// TODO: handle exception
//			e.printStackTrace();
			MyLog.d(GlobalConstant.TAG, "exception onCreateView HelpFragment: "+e.getMessage());
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
		cacheManager.clearActivityReportData();
		cacheManager.clearBloodOxygenData();
		cacheManager.clearBloodPressureData();
		cacheManager.clearGlucoData();
		cacheManager.clearWeightData();
		JSONObject object;
		try {
			object = new JSONObject(listUser.get(position-1).getToken());
			util.savePreferenceString(constant.USERID_IHEALTH_KEY, getActivity(), object.getString("UserID"));
			util.savePreferenceString(constant.ACCESSTOKEN_IHEALTH_KEY, getActivity(), object.getString("AccessToken"));
			util.savePreferenceString(constant.REFRESHTOKEN_IHEALTH_KEY, getActivity(), object.getString("RefreshToken"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Toast.makeText(getActivity(), getString(R.string.msg_ihealth_data_error), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		startActivity(new Intent(getActivity(),IHealthActivity.class));
		
	}


	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		refreshListUser();
	}

	
}
